package com.hzit.servlet;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hzit.dto.StudentDto;
import com.hzit.entity.PageResult;
import com.hzit.entity.R;
import com.hzit.entity.Student;
import com.hzit.service.StudentService;
import com.hzit.service.impl.StudentServiceImpl;
import com.hzit.vo.StudentVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {

	private StudentService studentService;

	@Override
	public void init() throws ServletException {
		studentService = new StudentServiceImpl();
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 得到cmd参数
		final String cmd = req.getParameter("cmd");
		//2. 根据参数调用不同的方法
		if(StrUtil.isNotBlank(cmd)){
			if("search".equals(cmd)){
				search(req,resp);
			}
		}
	}
	//1. 条件查询带分页功能
	private void search(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
		R r = null;
		try {
			//1.1 得到前羰传入的分页参数
			int page = Integer.parseInt(req.getParameter("page"));
			int pageSize = Integer.parseInt(req.getParameter("pageSize"));
			String stud = req.getParameter("stud");
			StudentVo vo = JSON.parseObject(stud, StudentVo.class);
			//1.2 得到分页结果对象
			PageResult<StudentDto> pr = studentService.search(page,pageSize,vo);
			r = R.ok().put("pr",pr);

		}catch (Exception e){
			e.printStackTrace();
			r = R.error("出现了查询错误！");
		}
		//1.3 处理这个结果对象
		String s = JSON.toJSONString(r);
		//1.4 输出
		resp.getWriter().println(s);
		resp.getWriter().flush();
	}
}
